package uploadQRcodeBusiness;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import impl.TestServerBusinessImpl;
import models.GetRequestInputStream;
import models.MyConfig;
import models.ReturnJson;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Objects;

/**
 * Created by yangxianming on 2019/12/19.
 * 设计稿页面处理方法
 */
public class UploadQRcodeDispense implements TestServerBusinessImpl {
    @Override
    public String doIt(HttpServletRequest request, MyConfig myConfig) {
        ReturnJson returnJson = new ReturnJson();
        JSONObject jsonObject = GetRequestInputStream.getJson(request);
        String action = jsonObject.getString("action");
        String splitMark = myConfig.getSplitMark("splitMark");
        String appPath = myConfig.getPropertiesConfig().getProperties().getProperty("appPath");
        String uploadQRcodePath = splitMark + "data" + splitMark + "uploadQRcode" + splitMark;

        if (Objects.equals(action, "getResult")){
            String fileName = jsonObject.getString("fileName");
            if (fileName.contains(".burn.")){
                returnJson.setApiStatus(0);
                returnJson.setErrorMsg("目标文件已被焚毁，贿赂小明10元可以帮助从灰烬中恢复文件");
                return returnJson.toString();
            }

            String resultPath = appPath + uploadQRcodePath + fileName + splitMark + "result.txt";
            JSONArray resultList = readLog(resultPath);

            //修改目录名
            File old = new File(appPath + uploadQRcodePath + fileName);
            File newName = new File(appPath + uploadQRcodePath + ".burn." +fileName);
            old.renameTo(newName);

            returnJson.setApiStatus(1);
            returnJson.setResult(resultList);
            return returnJson.toString();
        }

        if (Objects.equals(action, "getList")){
            HashMap<Long, JSONObject> dirList = new HashMap<Long, JSONObject>();
            File files = new File(appPath + uploadQRcodePath);
            ArrayList<Long> sortTime = new ArrayList<Long>();
            for (File file: files.listFiles()){
                JSONObject oneDir = new JSONObject();
                if (file.isDirectory()){
                    String fullName = file.getName();
                    String time = fullName.substring(fullName.length()-13);
                    String fileName = fullName.substring(0, fullName.length()-13);
                    boolean burn = false;
                    boolean resultFile = false;     //true有结果  false没结果
                    if (fileName.contains(".burn.")){
                        burn = true;
                        fileName = fileName.substring(6);
                    }else {
                        //可能有的目录还没有result文件
                        for (File innerFile: file.listFiles()){
                            if (Objects.equals(innerFile.getName(), "result.txt")){
                                resultFile = true;
                                break;
                            }
                        }
                    }
                    oneDir.put("resultFile", resultFile);

                    sortTime.add(Long.valueOf(time));
                    oneDir.put("fullName" , fullName);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        String t = sdf.format(Long.valueOf(time));
                        oneDir.put("time" , t);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    oneDir.put("fileName" , fileName);
                    oneDir.put("burn" , burn);

                    dirList.put(Long.valueOf(time), oneDir);
                }
            }
            Collections.sort(sortTime);
            Collections.reverse(sortTime);
            JSONArray sortList = new JSONArray();
            for (long t: sortTime){
                sortList.add(dirList.get(t));
            }

            returnJson.setApiStatus(1);
            returnJson.setResult(sortList);
            return returnJson.toString();
        }

        if (Objects.equals(action, "unzip")){
            String f = jsonObject.getString("fileName");
            String fileName = f.substring(f.lastIndexOf("\\") + 1, f.length());
            String dirPath = appPath + uploadQRcodePath + splitMark + fileName;

            //创建目录
            dirPath = dirPath.replace(".", "");
            File aDir = new File(dirPath);

            if (aDir.mkdir()){
                //"C:\Program Files\WinRAR\WinRAR.exe" x -y D:\javaWorkSpace\testServer2\web\\data\designs\koufu\qrcode.zip1580709884551 D:\javaWorkSpace\testServer2\web\\data\designs\koufu\25\a
                String whereWinrar = myConfig.getPropertiesConfig().getProperties().getProperty("winrarPath");
                String system = myConfig.getPropertiesConfig().getProperties().getProperty("system");
                String command = "";
                if (Objects.equals(system, "win")){
                    command = whereWinrar + " x -y " + appPath + uploadQRcodePath + fileName + " " + dirPath;
                }
                if (Objects.equals(system, "linux")){
                    command = whereWinrar + " -o " + appPath + uploadQRcodePath + fileName + " -d " + dirPath;
                }
                System.out.println(command);
                Runtime runtime = Runtime.getRuntime();
                try {
                    Process process = runtime.exec(command);
                    while (process.isAlive()){
                        System.out.println("unziping");
                        Thread.sleep(200);
                    }
                    //验证是否解压生成文件,有文件才给与上传
                    File file = new File(dirPath);
                    for (File oneFile: file.listFiles()){
                        if (oneFile.getName().startsWith(".")){
                            //跳过 . 开头的隐藏文件
                            continue;
                        }
                        String uploadPath = dirPath + splitMark + oneFile.getName() + splitMark;
                        System.out.println("uploadPath： " + uploadPath);
                        UploadOSS uploadOSS = new UploadOSS(uploadPath, dirPath + splitMark);
                        uploadOSS.start();
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            returnJson.setApiStatus(1);
            returnJson.setResult("ok");
            return returnJson.toString();
        }

        returnJson.setResult(0);
        returnJson.setErrorMsg("action not support");
        return null;
    }

    private JSONArray readLog(String fileName){
        JSONArray logInfo = new JSONArray(); //保存日志内容
        File file = new File(fileName);
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null){
                logInfo.add(line);
            }
            bufferedReader.close();
        }catch (Exception e){
//            System.out.println("reading log exception!!");
            logInfo.add("read log exception!!");
//            e.printStackTrace();
        }finally {
            if (bufferedReader != null){
                try {
                    bufferedReader.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
        return logInfo;
    }

    private boolean delFile(File file) {
        if (!file.exists()) {
            return false;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                delFile(f);
            }
        }
        return file.delete();
    }
}
